package service

import (
	"context"
	"elflog/common/errs"
	"math"
	"time"
)

// 清理log
func (a *ModuleLogService) RealDeleteLogByMaxSaveCount(ctx context.Context, loggerId string, maxCount int) (int, error) {
	const deleteSql = "delete from tb_log l where l.logger_id = ? and l.deleted_at is null and l.id in (select id from (select id from tb_log b where b.deleted_at is null order by b.time desc limit ?,?) as t)"
	result := a.dao.Dao.GetDb(ctx).Exec(deleteSql, loggerId, maxCount, math.MaxInt64)
	if result.Error != nil {
		return 0, errs.NewInternal().WithError(result.Error)
	}
	return int(result.RowsAffected), nil
}

func (a *ModuleLogService) RealDeleteLogByMaxSaveDuration(ctx context.Context, loggerId string, maxDuration int) (int, error) {
	const deleteSql = "delete from tb_log l where l.logger_id = ? and l.deleted_at is null and l.time<= ?"
	result := a.dao.Dao.GetDb(ctx).Exec(deleteSql, loggerId, time.Now().Add(-time.Duration(maxDuration)*time.Second))
	if result.Error != nil {
		return 0, errs.NewInternal().WithError(result.Error)
	}
	return int(result.RowsAffected), nil
}
